<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
  <title>C++ Tutorial: Pointers II
</title>
  <meta
 content="C++ Tutorial: Void Pointers" name="description" />
  <meta
 content="C++ Tutorial, Void Pointers, Arrays, Pointers to Pointers"
 name="keywords" />
  <meta http-equiv="Content-Type"
 content="text/html; charset=ISO-8859-1" />
  <link type="text/css" rel="stylesheet" href="../images/bogostyleWidePre.css" />
</head>
<body>
<div id="page" align="center">
<div id="content" style="width: 800px;">
<div id="logo">
<div class="whitetitle" style="margin-top: 70px;">bogotobogo </div>
</div>
<div id="topheader">
<div class="headerbodytext" align="left"><br />
<strong>Bogotobogo</strong><br />
contact@bogotobogo.com </div>
<div class="smallgraytext" id="toplinks"><a href="../index.html">Home</a>
| <a href="../sitemap.html">Sitemap</a>
| <a href="../blog" target="_blank">Contact Us</a>
</div>
</div>
<div id="menu">
<div class="smallwhitetext" style="padding: 9px;" align="right"><a
 href="../index.html">Home</a>
| <a href="../about_us.html">About Us</a>
| <a href="../products.html">Products</a>
| <a href="../our_services.html">Our Services</a>
| <a href="../blog" target="_blank">Contact Us</a>
</div>
</div>
<div id="submenu">
<div class="smallgraytext" style="padding: 9px;" align="right">
<a href="../gif.html">Gif</a> 
|<a href="../java_applet.html">JavaApplet/Web Start</a>
| <a href="../flash.html">Flash</a>
| <a href="../shockwave.html">ShockWave</a>
| <a href="../svg.html">SVG</a>
| <a href="../iPhone.html">iPhone/iPad</a>
| <a href="../android.html">Android</a>
| <a href="../OnHTML5.html">HTML5</a>
| <a href="../Algorithms/algorithms.html">Algorithms</a>
| <a href="../News/NewsMain.html">News</a>
| <a href="../cplusplus/cpptut.html">C++</a>
| <a href="../Java/tutorial/on_java.html">Java</a>
| <a href="../php/phptut.html">PHP</a>
| <a href="../DesignPatterns/introduction.html">Design Patterns</a>
| <a href="../python/pytut.html">Python</a> 
| <a href="../CSharp/.netframework.html">C#</a>
| <a href="../forums.html">Forums</a> 
| <a href="../VisualBasicSQL/introduction.html">Visual Basic</a>
</div>
</div>

<div id="contenttext">
<br />
<!-- Use of this code assumes agreement with the Google Custom Search Terms of Service. -->
<!-- The terms of service are available at http://www.google.com/cse/docs/tos.html -->
<form name="cse" id="searchbox_demo" action="http://www.google.com/cse">
  <input type="hidden" name="cref" value="" />
  <input type="hidden" name="ie" value="utf-8" />
  <input type="hidden" name="hl" value="" />
  <input name="q" type="text" size="40" />
  <input type="submit" name="sa" value="Search" />
</form>
<script type="text/javascript" src="http://www.google.com/cse/tools/onthefly?form=searchbox_demo&lang="></script>


<br />
<div style="padding: 10px;"><span class="titletext">C++ Tutorial -   Pointers II</span></div>

<div id="bookmarkshare">
<script type="text/javascript">var addthis_config = {"data_track_clickback":true};</script>
<a class="addthis_button" href="http://www.addthis.com/bookmark.php?v=250&amp;username=khhong7"><img src="http://s7.addthis.com/static/btn/v2/lg-share-en.gif" width="125" height="16" alt="Bookmark and Share" style="border:0"/></a><script type="text/javascript" src="http://s7.addthis.com/js/250/addthis_widget.js#username=khhong7"></script>
</div>


<img src="../images/cplusplus/cpp_logo.jpg" alt="cplusplus logo"/>

<div class="bodytext" style="padding: 12px;" align="justify"> 
<div class="subtitle_2nd" id="FullList">Full List of C++ Tutorials</div>
<ul>
   <li><a href="cpptut.html">C++ Home</a> </li>
   <li><a href="string.html">String</a> </li>
   <li><a href="constructor.html">Constructor</a> </li>
   <li><a href="operatoroverloading.html">Operator Overloading</a> </li>
   <li><a href="virtualfunctions.html">Virtual Functions</a></li>
   <li><a href="dynamic_cast.html">Dynamic Cast Operator</a></li>
   <li><a href="typecast.html">Type Cast Operators</a></li>
   <li><a href="autoptr.html">Class auto_ptr</a></li>
   <li><a href="templates.html">Templates</a></li>
   <li><a href="references.html">References for Built-in Types</a></li>
   <li><a href="valuevsreference.html">Pass by Value vs. Pass by Reference</a></li>
   <li><a href="memoryallocation.html">Memory Allocation</a></li>
   <li><a href="friendclass.html">Friend Functions and Friend Classes</a></li>
   <li><a href="functors.html">Functors (Function Objects)</a></li>
   <li><a href="statics.html">Static Variables and Static Class Members</a></li>
   <li><a href="exceptions.html">Exceptions</a></li>
   <li><a href="pointers.html">Pointers I</a></li>
   <li><a href="pointers2.html">Pointers II</a></li>
   <li><a href="pointers3.html">Pointers III</a></li>
   <li><a href="assembly.html">Taste of Assembly</a></li>
   <li><a href="smallprograms.html">Small Programs</a></li>
   <li><a href="linkedlist.html">Linked List Examples</a></li>
   <li><a href="binarytree.html">Binary Tree Example Code</a></li>
   <li><a href="stl.html">Standard Template Library (STL)</a></li>
   <li><a href="stl2.html">Standard Template Library (STL) II - Maps</a></li>
   <li><a href="stl3_iterators.html">Standard Template Library (STL) III - Iterators</a></li>
   <li><a href="slicing.html">Object Slicing and Virtual Table</a></li>
   <li><a href="this_pointer.html">The this Pointer</a></li>
   <li><a href="stackunwinding.html">Stack Unwinding</a></li>
   <li><a href="upcasting_downcasting.html">Upcasting and Downcasting</a></li>
   <li><a href="object_returning.html">Object Returning</a></li>
   <li><a href="private_inheritance.html">Private Inheritance</a></li>
   <li><a href="cplusplus_keywords.html">C++_Keywords</a></li>
   <li><a href="multithreaded.html">Multi-Threaded Programming - Terminology</a></li>
   <li><a href="multithreaded2A.html">Multi-Threaded Programming II - Native Thread for Win32 (A) </a></li>
   <li><a href="multithreaded2B.html">Multi-Threaded Programming II -  Native Thread for Win32 (B) </a></li>
   <li><a href="multithreaded2C.html">Multi-Threaded Programming II -  Native Thread for Win32 (C) </a></li>
   <li><a href="multithreaded2.html">Multi-Threaded Programming II - C++ Thread for Win32</a></li>
   <li><a href="multithreaded3.html">Multi-Threaded Programming III - C++ Class Thread for Pthreads</a></li>
   <li><a href="multithreadedDebugging.html">Multithread Debugging</a></li>
   <li><a href="embeddedSystemsProgramming.html">Embedded Systems Programming</a></li>
   <li><a href="boost.html">Boost</a></li>
   <li>Programming Questions and Solutions
    <ul>
       <li><a href="quiz_strings_arrays.html">Strings and Arrays</a></li>
       <li><a href="quiz_linkedlist.html">Linked List</a></li>
       <li><a href="quiz_recursion.html">Recursion</a></li>
       <li><a href="quiz_bit_manipulation.html">Bit Manipulation</a> </li>
       <li><a href="google_interview_questions.html">140 Google Interview Questions</a> </li>
    </ul>
   </li>
</ul>
</div>
<br />
	<br />
	<img src="images/pointers2/PahlDang.png" alt="PahlDang"/>
	<br /><br />
<br />

<br />
<div class="bodytext" style="padding: 12px;" align="justify">

<div class="subtitle" id="voidpointers">void Pointers</div>
<p>The <strong>void*</strong> doesn't mean it points to nothing. Actually, it is pointing something but we just don't know the exact type of object it is pointing to.</p> 
<p>Let's take a look at the famous <strong>swap()</strong> function</p>
<pre>
#include &lt;iostream&gt;
using namespace std;

void swap(int *ap, int *bp)
{
	int temp;
	temp = *ap;
	*ap = *bp;
	*bp = temp;
}
int main()
{
	int a = 7, b = 17;
	cout << "a = " << a << " b = " << b << endl;
	swap(&a, &b);
	cout << "a = " << a << " b = " << b << endl;
	return 0;
}
</pre>
<p>With an output:</p>
<pre>
a = 7 b = 17
a = 17 b = 7
</pre>
<p>The <strong>swap()</strong> function has been used to illustrate how the pointers are working. However, we want to discuss the <strong>type</strong> of variables we're swapping. Here, integers are being swapped. Can we tell where the <strong>type information</strong> is used in the code? Not clear? What the code is doing is <strong>exchanging bit patterns</strong> reside in the memory pointed by the pointers to <strong>integers</strong>. Algorithmically it's simply a bit pattern rotation. How the <strong>integer</strong> is used?
When we copy the bit pattern, we do in 4-byte unit.</p>
<p>So, the basic function of the code is copying bit pattern and it does not care much about the <strong>type</strong>. It's not that tough for us to make the code <strong>type independent</strong> if we use <strong>void*</strong>.</p>  

<p>The primary use for <strong>void*</strong> is for passing pointers to functions that are not allowed to make assumptions about the type of the object and for returning untyped objects from functions. To use such an object, we should use explicit type conversion.</p>
<p>A <strong>void*</strong> pointer is a pointer that point to a value that has no type. 
A void pointer seems to be of limited use. However, when combined with the ability to cast such a pointer to another type, they are quite useful.</p>
<p>
Since it has an undetermined length and undetermined dereference properties,
void pointer can point to any data type, from an integer value or a float to a string of characters. That's why it is sometimes referred to as a <strong>generic</strong> pointer.</p>
<p>
However, on the other hand, void pointers have a great limitation such as the data pointed by them cannot be directly dereferenced since there is no type information to guide the compiler in interpreting the underlying bit pattern. So, we will always have to cast the address in the void pointer to some other pointer type that points to a concrete data type before dereferencing it.</p>
<p>A void pointer is declared like a normal pointer, using the void keyword as the pointerï¿½s type:</p>
<pre>
void *pVoid;
</pre>
<p>Here is a simple example using the <strong>void*</strong> pointer.</p>
<pre>
#include &lt;iostream&gt;  
using namespace std;  

enum Type  {  
   INT,  
   FLOAT,  
   STRING,  
 };  

void Display(void *pVoid, Type eType)  {    
   switch (eType)  {  
	case INT:  
 		cout << *(int*)pVoid << endl;  
		break;  
	case FLOAT:  
		cout << *(float*)pVoid << endl;  
		break;  
	case STRING:  
		cout << (char*)pVoid << endl;  
		break;  
   }  
}    

int main()  
{  
   int a = 10;  
   float b = 987.654;  
   char *c = 
	"Art is a lie that makes us realize the truth.";  
   Display(&a, INT);  
   Display(&b, FLOAT);  
   Display(c, STRING);  
   return 0;  
} 
</pre>
<p>Output is:</p>
<pre>
10
987.654
Art is a lie that makes us realize the truth.
</pre>
<p>In the code above, the function <strong>Display()</strong> is called with an argument of <strong>&amp;a</strong>, <strong>&amp;b</strong>, and <strong>c</strong> which are pointers. Then it gets them as <strong>void *pVoid</strong> which is a <strong>void*</strong> pointer type.</p>
<p>Inside the <strong>Display()</strong> function, it prints out after casting them to appropriate types and dereferencing them.</p>
<p>Here is an example that shows there is no automatic conversion of a <strong>void*</strong> pointer to a pointer to a particular type.</p>
<pre>
#include &lt;iostream&gt;  

int main()  
{  
   int i;
   int *pi = 0;
   char *pc = 0;
   void *pVoid;

   pVoid = pi;
   pVoid = pc;

   const int *pci = &i;	// pointer to const int
   pVoid = pci;		// error
   return 0;  
} 
</pre>
<p>If we compile it, we get an error:</p>
<pre>
cannot convert from 'const int *' to 'void *'
</pre>
<p>What we need to do is assign the <strong>const int *</strong> to <strong>const void *</strong> not to <strong>void *</strong> or we take the constantness from the pointer to const int, pci, as in the following code.</p>
<pre>
#include &lt;iostream&gt;  

int main()  
{  
   int i;
   int *pi = 0;
   char *pc = 0;
   void *pVoid;

   pVoid = pi;
   pVoid = pc;

   const int *pci = &i;			// pointer to const int
   //pVoid = pci;			// error
   <font color="blue">const void *pcVoid = pci;</font>		// using const void*
   <font color="blue">pVoid = const_cast&lt;int *&gt;(pci);</font>	// cast away constantness
   return 0;  
} 
</pre>
<br />
<br />


<div class="subtitle_2nd" id="voidpointers2">void Pointers II</div>
<p>Not satisfied with my description. Then, how about the following excerpts from a new book "Programming ...., 2008" by Bjarne Stroustrup.</p>
<p>The type <strong>void*</strong> means "<strong>pointer to some memory that the compiler doesn't know the type of</strong>."<br />
We are using <strong>void*</strong> when we want to transmit an address between pieces of code that really don't know each other's type.</p>
<p>Normally we use it in the following cases:</p>
<ul>
	<li>A type of pointer that points to memory without knowing what kinds of objects reside in that memory.</li>
	<li>An operation to tell the compiler what kind of type to assume for memory pointed to by one of those pointers.</li>
</ul>
<p>There are no objects of type <strong>void</strong>. but we use <strong>void</strong> to mean <strong>no value returned</strong>:</p>
<pre>
void v;     // error because there are no object of type void
void v();   // v() return nothing - v() does not return an object of type void
</pre>
<p>A pointer to any object type can be assigned to a <strong>void*</strong>:</p>
<pre>
void* ptr1 = new int;          //OK: int* converted to void*
void* ptr2 = new double[100]   //OK: double* converted to void*
</pre>
<p>Because the compiler doesn't know what a <strong>void*</strong> points to, we should let the compiler know:</p>
<pre>
void function(void *pvoid)
{
	void* pvoid2 = pvoid;     // copying is OK (copying is what void*s are for)
	double* pd = pvoid;       // error: cannot convert void* to double*
	*pvoid = 7;               // error: cannot dereference a void*
	int* pi = static_cast<int*>(pvoid)  // OK: explicit conversion
}
</pre> 

<br />
	<br />
	<img src="images/pointers2/NamHaiBada.png" alt="NamHaiBada"/>
	<br /><br />
<br />
<br />


<div class="subtitle_2nd" id="voidpointers3">void Pointers III</div>
<p>In this section, we will see another example of using <strong>void*</strong> related to <strong>generic</strong> programming. It's a kind of C-way of making a code generic which is equivalent of using templates in C++. Though there are lots of benefit of using templates, one of the downside of template is that the executable could become huge if we use the generic code for hundreds of different types such as int, float, student object, shape object etc. The C version of code we're going to make does not have that issue though it could become harder to code correctly. </p>
<p>Here is a simple swap program for integer. Later, we'll make it generic using <strong>void*</strong>.</p>
<pre>
#include &lt;iostream&gt;
using namespace std;

void swap(int *ap, int *bp) {
	int temp = *ap;
	*ap = *bp;
	*bp = temp;
}

int main()
{
	int a = 10, b = 20;
	cout << a << " , " << b << endl;
	swap(&a, &b);
	cout << a << " , " << b << endl;
}
</pre>
<p>Output from the run:</p>
<pre>
10 , 20
20 , 10
</pre>
<p>Now, we want the <strong>swap()</strong> to work for any types, int, char, char *, float, double, etc. So, we decided to use our <strong>void *</strong>. Let's look at the code below and find out what's wrong in the code.</p>
<pre>
void swap(<font color="blue">void *</font>vp1, <font color="blue">void *</font>vp2) {
	<font color="blue">void temp = *vp1;</font>
	*vp1 = *vp2;
	*vp2 = temp;
}
</pre>
<ul>
	<li>We can't declare a variable as a void type:
<pre>
void temp 
</pre>
	</li>
	<li>We're not allowed dereference void pointer:
<pre>
void temp = <font color="blue">*vp1</font>;
</pre>
	Why not? <br />
	Because we don't know the type we don't know how many bytes we should embrace from the memory. Should we get 1 byte, 2 bytes, or 4 bytes? We do not have the type information about the thing being addressed at all. <br />
	To address this problem for unknown type (or size), we need to get more information from the caller. In other words, the called should pass in the size info as an argument. 
	</li>
</ul>
<p>Here is the final code for generic swap().</p>
<pre>
#include &lt;iostream&gt;
using namespace std;

void swap (void *vp1, void *vp2, const int size) {
	char *buffer = (char *)malloc(sizeof(char)*size);
	memcpy(buffer, vp1, size);
	memcpy(vp1, vp2, size);
	memcpy(vp2, buffer, size);
	free(buffer);
}

int main()
{
	int a = 10, b = 20;
	cout << a << " , " << b << endl;
	swap(&a, &b, sizeof(int));
	cout << a << " , " << b << endl;
	cout << endl;

	char *puppy = strdup("Wow");
	char *kitty = strdup("Mew");

	cout << puppy << " , " << kitty << endl;
	swap(&puppy, &kitty, sizeof(char **));
	cout << puppy << " , " << kitty << endl;
}
</pre>
<p>Output is: </p>
<pre>
10 , 20
20 , 10

Wow , Mew
Mew , Wow
</pre>
<p>In <strong>char *buffer</strong>, actually we don't care it's character or not. All we want is to have enough bytes to store something with <strong>size</strong>-byte. In other words, we need storage.</p>
<p>The function <strong>memcpy()</strong> is similar to <strong>strcpy()</strong> which copies bytes from one location to another location kept on copying until it found <strong>'\0'</strong> and copy the <strong>'\0'</strong> as well. The <strong>memcpy()</strong> is not dedicated to characters and is more generic. It does not pay attention to the <strong>'\0'</strong>. We have to explicitly tell it how many bytes to copy to memory location.</p>
<br />
<br />

<div class="subtitle" id="pointersandarrays">Pointers and Arrays</div>
<p><i>"The use of pointer arithmetic is mainly a matter of personal taste; some programmers consider pointer-based algorithms to be more elegant that their array-based counterparts; others simply find them harder to read. Certainly the fact that arrays are passed as pointers makes it natural to write subroutines in the pointer style."</i> - Programming Language Pragmatics, 3rd ed. 2009 (Michael L. Scott).</p>
<p>Pointers have a close relationship with arrays. In fact, an array name is a constant pointer to the first element of the array. Since the elements of an array are stored in a contiguous block of memory, we can use the array name as a pointer to access to elements.</p>
<pre>
int myArray[100];
int *pi;
</pre>
<p>We can assign array name to a pointer.</p>
<pre>
pi = myArray;
</pre>
<p>Then, <strong>pi</strong> and <strong>myArray</strong> are equivalent. The only difference is that we could change the value of pointer <strong>pi</strong> by another one, whereas <strong>myArray</strong> will always point to the first of the 100 elements of type <strong>int</strong> with which it was defined since the array name <strong>myArray</strong> is a constant pointer to the first element of the array . </p>
<p>So, the following assignment is illegal.</p>
<pre>
array = pi;
</pre>
<p>Again, the reason is we cannot assign a value to a constant. Simple but easy to forget.</p>
<p>Here is a simple example showing the relationship between pointers and arrays.</p>
<pre>
#include &lt;iostream&gt;  
using namespace std;

static const int SIZE = 3;

void doubleScores(int * const array) {
	for (int i = 0; i < SIZE; i++) 
		array[i] *= 2;
}

void showScores(const int* const array) {
	for (int i = 0; i < SIZE; i++) 
		cout << array [i] << endl;
}

int main()  
{  	
	int scores[] = {68,72,75};

	cout << *scores << endl;
	cout << *(scores+1) << endl;
	cout << *(scores+2) << endl;

	doubleScores(scores);
	showScores(scores);

	return 0;
}
</pre>
<p>The code creates an array of scores and then displays them using the array name as a constant pointer. Then, it passes the array name as a constant pointer to a function to double the scores. Next, the code passes the array name to a function as a constant pointer to a constant to show the scores doubled.</p>
<br />

<div class="subtitle_2nd" id="arraynameaspointer">Array Name as a Constant Pointer</div>
<p>As mentioned before, because an array name is a constant pointer to the first element of the array, we can dereference the name to get the first element.</p>
<pre>
cout << *scores << endl;
</pre>
<p>We can randomly access array elements using an array name as a pointer through using pointer arithmetic. What we do is to add the position number of the element we want to access to the pointer before we dereference it.</p>
<pre>
	cout << *(scores+1) << endl;
	cout << *(scores+2) << endl;
</pre>
<p>In general, following two lines are equivalent.</p>
<pre>
array[i]
*(array + i)
</pre>
<br />
<div class="subtitle_2nd" id="passingarray">Passing an Array to a Function</div>
<p>Because an array name is a constant pointer, we can use it to pass an array to a function as shown below.</p>
<pre>
doubleScores(scores);
</pre>
<p>Our program passes to <strong>doubleScores()</strong> a constant pointer to the first element of the array. As we can see from the function header of <strong>doubleScores()</strong>, the array name is accepted as a constant pointer.</p>
<pre>
void doubleScores(int * const array) {
</pre>
<p>The function <strong>showScores</strong> also accepts <strong>scores</strong> as a pointer. However, as we can see from the function header, the function accepts it as a constant pointer to a constant.</p>
<pre>
void showScores(const int* const array) {
</pre>
<p>By passing the array in this way, We keep it safe from being modified inside the function. In fact, all we want to do here is just displaying the array elements.</p>
<br />
<br />
	<br />
	<img src="images/pointers2/SeoRakMt.png" alt="SeoRakMt"/>
	<br /><br />
<br />
<br />
<br />


<div class="subtitle" id="pointertospointer">Pointers to Pointers</div>
<p>The declaration of a pointer-to-pointer looks like </p>
<pre>
	int **ipp;
</pre>
<p>
where the two asterisks indicate that two levels of pointers are involved. </p>
<p>Let's look at the following simple example:</p>
<pre>
#include &lt;iostream&gt;  
using namespace std;

int main()  
{  	
	int i = 10;
	int *pi = &i;
	int **ppi = &pi;

	cout << i << "," <<  pi << "," << ppi << endl;
	cout << i << "," <<  *pi << "," << **ppi << endl;
	return 0;
}
</pre>
<p>Output is:</p>
<pre>
10,0017FF28,0017FF1C
10,10,10
</pre>


<p>What are the usages of pointers to pointers? <br />
One example for the use of  pointers to pointers is returning pointers from functions, via pointer arguments rather than as the formal return value. </p>
<pre>
#include &lt;iostream&gt;  
using namespace std;

int allocString(int len, char **ppChar) {
	char *p = new char[len + 1];
	if(p == NULL)
		return 0;
	*ppChar = p;
	return 1;
}

int main()  
{  	
	char *string = "Pablo Picasso!";
	char *copyString;
	if(allocString(strlen(string), &amp;copyString))
		strcpy(copyString, string);
	else	
		fprintf(stderr, "out of memory\n");

	cout << "string = " << string << endl;
	cout << "copyString = " << copyString << endl;

	return 0;
}
</pre>
<p>Output is:</p>
<pre>
string = Pablo Picasso!
copyString = Pablo Picasso!
</pre>
<p>Now, the function <strong>allocString()</strong> wants to <strong>return a pointer</strong> via its argument. The corresponding parameter will then have to be a pointer to a pointer, <strong>char **ppChar</strong>. The  function which tries to allocate memory for a string of length n, and which returns zero (``false'') if it fails and 1 (nonzero, or ``true'') if it succeeds, returning the actual pointer to the allocated memory via a pointer: </p>
<p>The example above is not a good way of memory allocation at all. But it shows how the pointer to a pointer is being used. Another better and more practical example that uses pointer to a pointer is deleting a node from the linked list which we'll discuss in later chapter of this tutorial such as <a href="linkedlist.html">linked list</a>.</p>
<p>Let's look at another example. We declare an array of cstrings:</p>

<img src="images/pointers2/arrayOfCStrings.png" alt="arrayOfCStrings"/>

<pre>
#include &lt;iostream&gt;
using namespace std;

void arrayTest(char **p) {
	cout << " *p = " << *p << endl;
	cout << " *(p+1) = " << *(p+1) << endl;
}

int main()
{
	char *notes[] = {"C#", "Eb", "A", "Bb", "F#"};
	char **pNotes[5];
	for (int i = 0; i < 5; i++) {
		pNotes[i] = &amp;notes[i];
		cout << "pNotes[" << i << "] = " << pNotes[i] << endl; 
		cout << "*pNotes[" << i << "] = " << *pNotes[i] << endl;
	}
	cout << endl;
	cout << "notes[1] =" << notes[1] << endl;
	cout << "notes[1] + 1 =" << notes[1] + 1 << endl;
	cout << "*(notes + 1) = " << *(notes + 1)<< endl;
	cout << "*(notes + 2) = " << *(notes + 2)<< endl;

	arrayTest(notes);
	return 0;

}
</pre>
<p>Output is:</p>
<pre>
pNotes[0] = 0017FF18
*pNotes[0] = C#
pNotes[1] = 0017FF1C
*pNotes[1] = Eb
pNotes[2] = 0017FF20
*pNotes[2] = A
pNotes[3] = 0017FF24
*pNotes[3] = Bb
pNotes[4] = 0017FF28
*pNotes[4] = F#

notes[1] =Eb
notes[1] + 1 =b
*(notes + 1) = Eb
*(notes + 2) = A
 *p = C#
 *(p+1) = Eb
</pre>
<p>Note that <strong>notes</strong> represent the same address as <strong>notes[0]</strong>. However, when we add <strong>1</strong>, compiler does point arithmetic differently. In other words, the <strong>1</strong> in <strong>notes+1</strong> hops to another <strong>cstring</strong> while the <strong>1</strong> in <strong>notes+1</strong> hops to another <strong>character</strong>.</p>
<p>So, in cases when we want to pass an array of character strings (<strong>char **notes</strong>) for string comparison with the key string, what we need is hopping array by array as we're doing in <strong>arrayTest()</strong> by passing an <strong>array of pointers</strong> to the cstring. In other words, we need just one hop (one string at a time) not two hops(one character at a time).</p>
<br />
<br />

<div class="subtitle_2nd" id="lsearch">Char **: Linear Search Example</div>
<br />
<img src="images/pointers2/arrayOfCStringsB.png" alt="arrayOfCStringsB"/>
<br />
<p>In this section, we're going to do linear search to find a matching cstrings for a key. The search routine is made generic using <strong>void *</strong>:</p>
<pre>
#include &lt;iostream&gt;
using namespace std;

int StrCmp(void *vp1, void *vp2)
{
	char *s1 = *(char **)vp1;
	char *s2 = *(char **)vp2;
	return strcmp(s1,s2);
}

void* lsearch(void *key, void *base, int n, int elemSize,
			  int (*cmpfn)(void *, void *))
{
	for(int i = 0; i < n; i++) {
		void *elemAddr = (char *)base + i * elemSize;
		if(cmpfn(key, elemAddr) == 0) return elemAddr;
	}
	return NULL;
}

int main()
{
	char *notes[] = {"C#", "Eb", "A", "Bb", "F#"};
	char *keyNote = "F#";
	char **found =
		(char **)lsearch(&keyNote, notes, 5, sizeof(char *), StrCmp);
	cout << "*found = " << *found;
	return 0;
}
</pre>
<p>Output is:</p>
<pre>
*found = F#
</pre>
<p>In the above code, let's look at the arguments of the <strong>lsearch()</strong> function:</p>
<pre>
char **found =
	(char **)lsearch(&keyNote, notes, 5, sizeof(char *), StrCmp);
</pre>
<p>We're passing in <strong>notes</strong> which is equivalent of <strong>&amp;notes[0]</strong> and we know it's really a <strong>char **</strong>.</p>
<p>In the 4th argument, we're passing in <strong>sizeof(char *)</strong> rather than <strong>sizeof(char **)</strong>, because we're interested in the <strong>byte width</strong> of each cstring element in the array. Though the size of <strong>char **</strong> is the same as <strong>char *</strong>, we want it to be <strong>char *</strong> for readability purpose by showing the real data type resides in the array.</p> 
<p>The last argument, <strong>StrCmp()</strong> is the comparison function for string and it's different from <strong>strCmp()</strong> of C-library.</p>
<p>For the first argument <strong>&keyNote</strong>, we could just pass in <strong>keyNote</strong> without <strong>&</strong>. But it's more consistent if we match the type of the <strong>notes</strong> which is <strong>char **</strong>. So, we're passing in <strong>&keyNote</strong>.</p>
<p>Let's look at the function <strong>StrCmp()</strong>.</p>
<pre>
int StrCmp(void *vp1, void *vp2)
{
	char *s1 = *(char **)vp1;
	char *s2 = *(char **)vp2;
	return strcpm(s1,s2);
}
</pre>
<p>In <strong>StrCmp()</strong>, when we're doing <strong>*(char **)vp1;</strong>, the <strong>(char **)</strong> means <strong>vp1</strong> is two hops away from the character string and really it is.</p>



<div id="rightpanel">
<div align="center">
</div></div>

<br /><br />
<br /><br />
<div class="subtitle_2nd" id="FullList">Full List of C++ Tutorials</div>
<ul>
   <li><a href="cpptut.html">C++ Home</a> </li>
   <li><a href="string.html">String</a> </li>
   <li><a href="constructor.html">Constructor</a> </li>
   <li><a href="operatoroverloading.html">Operator Overloading</a> </li>
   <li><a href="virtualfunctions.html">Virtual Functions</a></li>
   <li><a href="dynamic_cast.html">Dynamic Cast Operator</a></li>
   <li><a href="typecast.html">Type Cast Operators</a></li>
   <li><a href="autoptr.html">Class auto_ptr</a></li>
   <li><a href="templates.html">Templates</a></li>
   <li><a href="references.html">References for Built-in Types</a></li>
   <li><a href="valuevsreference.html">Pass by Value vs. Pass by Reference</a></li>
   <li><a href="memoryallocation.html">Memory Allocation</a></li>
   <li><a href="friendclass.html">Friend Functions and Friend Classes</a></li>
   <li><a href="functors.html">Functors</a></li>
   <li><a href="statics.html">Static Variables and Static Class Members</a></li>
   <li><a href="exceptions.html">Exceptions</a></li>
   <li><a href="pointers.html">Pointers I</a></li>
   <li><a href="pointers2.html">Pointers II</a></li>
   <li><a href="pointers3.html">Pointers III</a></li>
   <li><a href="assembly.html">Taste of Assembly</a></li>
   <li><a href="smallprograms.html">Small Programs</a></li>
   <li><a href="linkedlist.html">Linked List Examples</a></li>
   <li><a href="binarytree.html">Binary Tree Example Code</a></li>
   <li><a href="stl.html">Standard Template Library (STL)</a></li>
   <li><a href="stl2.html">Standard Template Library (STL) II - Maps</a></li>
   <li><a href="stl3_iterators.html">Standard Template Library (STL) III - Iterators</a></li>
   <li><a href="slicing.html">Object Slicing and Virtual Table</a></li>
   <li><a href="this_pointer.html">The this Pointer</a></li>
   <li><a href="upcasting_downcasting.html">Upcasting and Downcasting</a></li>
   <li><a href="object_returning.html">Object Returning</a></li>
   <li><a href="private_inheritance.html">Private Inheritance</a></li>
   <li><a href="cplusplus_keywords.html">C++_Keywords</a></li>
   <li><a href="multithreaded.html">Multi-Threaded Programming - Terminology</a></li>
   <li><a href="multithreaded2A.html">Multi-Threaded Programming II - Native Thread for Win32 (A) </a></li>
   <li><a href="multithreaded2B.html">Multi-Threaded Programming II -  Native Thread for Win32 (B) </a></li>
   <li><a href="multithreaded2C.html">Multi-Threaded Programming II -  Native Thread for Win32 (C) </a></li>
   <li><a href="multithreaded2.html">Multi-Threaded Programming II - C++ Thread for Win32</a></li>
   <li><a href="multithreaded3.html">Multi-Threaded Programming III - C++ Class Thread for Pthreads</a></li>
   <li><a href="multithreadedDebugging.html">Multithread Debugging</a></li>
   <li><a href="embeddedSystemsProgramming.html">Embedded Systems Programming</a></li>
   <li><a href="boost.html">Boost</a></li>
   <li>Programming Questions and Solutions
    <ul>
       <li><a href="quiz_strings_arrays.html">Strings and Arrays</a></li>
       <li><a href="quiz_linkedlist.html">Linked List</a></li>
       <li><a href="quiz_recursion.html">Recursion</a></li>
       <li><a href="quiz_bit_manipulation.html">Bit Manipulation</a> </li>
       <li><a href="google_interview_questions.html">140 Google Interview Questions</a> </li>
    </ul>
   </li>
</ul>
<br /><br />


<br />


<br />
<br />
<br />


</div>
</div>
<div class="smallgraytext" id="footer"><a href="../index.html">Home</a>
| <a href="../about_us.html">About Us</a>
| <a href="../products.html">products</a>
| <a href="../our_services.html">Our Services</a>
| <a href="#">Contact Us</a>
| Bogotobogo &copy; 2011 | <a target="_blank" href="http://www.bogotobogo.com">Bogotobogo </a>
</div>
</div>
</div>
</body>
</html>
